package com.cr.front.authentication.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cr.common.exception.ServiceException;
import com.cr.front.audit.pojo.dto.AuditSaveParam;
import com.cr.front.audit.service.AuditService;
import com.cr.front.authentication.mapper.AuthenticationMapper;
import com.cr.front.authentication.pojo.dto.AuthenticationSaveParam;
import com.cr.front.authentication.pojo.entity.Authentication;
import com.cr.front.authentication.pojo.vo.AuthenticationVO;
import com.cr.front.authentication.pojo.vo.LongRentVO;
import com.cr.front.authentication.service.AuthenticationService;
import com.cr.front.user.mapper.UserMapper;
import com.cr.front.user.pojo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Slf4j
@Service
public class AuthenticationServiceImpl implements AuthenticationService {
    @Autowired
    private AuthenticationMapper authenticationMapper;
    @Autowired
    private AuditService auditService;


    @Override
    public void addAuthentication(AuthenticationSaveParam authenticationSaveParam) {
        log.warn("入参{}",authenticationSaveParam);
        long userId;
        String obj = StpUtil.getLoginId().toString();
        if (obj != null) {
            userId = Long.parseLong(obj);
        }else {
            throw new ServiceException("未登录");
        }
        Authentication authentication = new Authentication();
        BeanUtils.copyProperties(authenticationSaveParam, authentication);
        authentication.setUserId(userId);
        //yyyy-mm-dd格式字符串转date
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date validStart = null;
        Date validEnd = null;
        Date birthday = null;
        try {
            validStart = sdf.parse(authenticationSaveParam.getValidDateStart());
            validEnd = sdf.parse(authenticationSaveParam.getValidDateEnd());
            birthday = sdf.parse(authenticationSaveParam.getBirthday());
            //设置出生日期
            authentication.setBirthday(birthday);

        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        Date now = new Date();
        //证件是否有效
        if(validEnd.after(now) && now.after(validStart)){
            authentication.setStatus(0);
            authentication.setValidDateStart(validStart);
            authentication.setValidDateEnd(validEnd);
        }else{
            throw new ServiceException("证件有效日期错误");

        }
        //设置审核中
        authentication.setAuditing(1);
        //使同类型的证件标注未选中
        Integer authenticationType = authenticationSaveParam.getAuthenticationType();
        checkDuplicateAuthentication(userId, authenticationType);
        //选中新增的证件
        authentication.setSelection(0);
        authentication.setApplicationId(generateUniqueOrderNumber());
        authenticationMapper.insert(authentication);
        AuditSaveParam auditSaveParam = new AuditSaveParam();
        auditSaveParam.setApplicationId(authentication.getApplicationId());
        auditService.addAuthenticationAudit(auditSaveParam);



    }

    @Override
    public AuthenticationVO getAuthenticationDetail() {
        long userId;
        String obj = StpUtil.getLoginId().toString();
        if (obj != null) {
            userId = Long.parseLong(obj);
        }else {
            throw new ServiceException("未登录");
        }
        AuthenticationVO authenticationVO =new AuthenticationVO();
        QueryWrapper<Authentication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        //审核通过
//        queryWrapper.eq("auditing", 0);
        //选中
        queryWrapper.eq("selection", 0);
        List<Authentication> list = authenticationMapper.selectList(queryWrapper);
        if(!list.isEmpty()){
            BeanUtils.copyProperties(list.get(0), authenticationVO);
            return authenticationVO;
        }
        return null;
    }

    private void checkDuplicateAuthentication(Long userId, Integer authenticationType){
        UpdateWrapper<Authentication> updateWrapper= new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId);
//        updateWrapper.eq("authentication_type",authenticationType);
        updateWrapper.set("selection",1);
        authenticationMapper.update(null, updateWrapper);

    }

    // 生成唯一的订单号
    private String generateUniqueOrderNumber() {
        // 这里可以根据业务需求生成唯一的订单号，例如使用数据库的序列、UUID、时间戳+随机数等方式生成
        Random random = new Random();
        long currentTime = System.currentTimeMillis();
        long orderNumber = currentTime * 1000 + random.nextInt(1000); // 保证足够唯一性
        return String.valueOf(orderNumber);
    }
}
